import json
import os
import time
import requests

from common import write_to_file
from common import factory_connection
from common import create_token
from common import close_connection
from common import get_fcodebyorder
#from message import RabbitMQ
from rabbitmq import RabbitMQ



home_dir = os.path.expanduser("~")
file_path = os.path.join(home_dir, 'Downloads', 'order.tsv')
headers = { 'Authorization': create_token(),'Content-Type': 'application/json'}
rabbitmq_source = None
sql_list = ['swan','wf','pn','peach','meow','colorful','newlook','star']



def get_express_no(factory_code,shipment_id):
    connection = factory_connection(factory_code)
    cursor = connection.cursor()
    cursor.execute(f'SELECT express_no FROM opr_shipment WHERE id = {shipment_id}')
    result = cursor.fetchone()
    if result:
        express_no = result[0]
    close_connection(connection)
    return express_no

#获取当前水洗码的状态
def barcode_status(factory_code,barcode):
    connection = factory_connection(factory_code)
    cursor = connection.cursor()
    cursor.execute(f'SELECT `status` FROM opr_product WHERE barcode = "{barcode}"')
    results = cursor.fetchall()
    if results:
        first_tuple = results[0]
        status = first_tuple[0]
        print(f"{barcode}: {status}")
    close_connection(connection)
    return status



#校验出厂单等待物流下单成功
def check_express_status(factory_code,order_no,shipment_id):
    max_wait_time = 5
    current_wait_time = 0
    while True:
        express_no = get_express_no(factory_code,shipment_id)
        if express_no is not None:
            print("校验通过" + express_no)
            break
        else:
            print(f"{order_no}运单号为空. 等待一秒.")
            time.sleep(1)  # 等待1秒
            current_wait_time += 1
            if current_wait_time >= max_wait_time:
                print("校验超时")
                write_to_file("~/Downloads/timeout.tsv",factory_code, order_no)
                break



#获取鞋子副码
def pair_barcode(factory_code,barcode):
    connection = factory_connection(factory_code)
    cursor = connection.cursor()
    cursor.execute(f'SELECT barcode FROM opr_product WHERE companion_id = (SELECT id FROM opr_product WHERE barcode = "{barcode}")')
    results = cursor.fetchall()

    if results:
        first_tuple = results[0]
        result_string = first_tuple[0]
        print(f"{barcode}: {result_string}")
        return result_string
    else:
        return None
    close_connection(connection)



#质检
def product_qualified(factory_code, barcode):
    status = barcode_status(factory_code,barcode)
    if int(status) < 6:
        URL = f"https://{factory_code}.haishenxiyi.net/api/product/{barcode}"
        response = requests.get(URL,headers=headers)
        result = json.loads(response.text)
        code = result.get('code')
        print(URL)
        print("Response Text:", response.text)
        if code == 200:
            print('质检查询请求成功！')
            pairbarcode = pair_barcode(factory_code, barcode)
            if pairbarcode is None:
                qual_url = f"https://{factory_code}.haishenxiyi.net/api/product/{barcode}/qualified"
                qual_response = requests.post(qual_url,headers=headers)
                print(qual_url)
                print("Response Text:", qual_response.text)
            else:
                p_url = f"https://{factory_code}.haishenxiyi.net/api/product/{pairbarcode}"
                p_response = requests.get(p_url, headers=headers)
                p_result = json.loads(p_response.text)
                p_code = p_result.get('code')
                print(URL)
                print("Response Text:", p_response.text)
                if p_code == 200:
                    pair_url = f"https://{factory_code}.haishenxiyi.net/api/product/{barcode}/{pairbarcode}/qualified"
                    pair_response = requests.post(pair_url,headers=headers)
                    print(pair_url)
                    print("Response Text:", pair_response.text)
        else:
            print(f'查询质检详情失败，状态码：{response.status_code}')


#配附件扫描接口
def attachment_scan(factory_code,barcode):
    status = barcode_status(factory_code, barcode)
    if status == "6":
        connection = factory_connection(factory_code)
        cursor = connection.cursor()
        cursor.execute(f"SELECT barcode FROM opr_attachment WHERE product_id = (SELECT id FROM opr_product WHERE barcode = '{barcode}') and flag & 512 != 512")
        result = cursor.fetchall()
        for row in result:
            barcodes = row
            att_barcode = barcodes[0]
            url = f"https://{factory_code}.haishenxiyi.net/api/product/{barcode}/attachment/{att_barcode}/scan"
            response = requests.post(url,headers=headers)
            print(url)
            print(response.text)
        close_connection(connection)


#包装
def wrap_barcode(factory_code, barcode):
    status = barcode_status(factory_code, barcode)
    if status == "7":
        URL = f"https://{factory_code}.haishenxiyi.net/api/product/wrap/{barcode}"
        response = requests.get(URL,headers=headers)
        result = json.loads(response.text)
        code = result.get('code')
        print(URL)
        print("Response Text:", response.text)
        if code == 200:
           print('包装成功！')
           label_url = f"https://{factory_code}.haishenxiyi.net/api/product/checkLable/{barcode}"
           label_response = requests.get(label_url,headers=headers)
           print(label_url)
           print(label_response.text)
        else:
            print('包装失败！')

#拣货
def picking_barcode(factory_code,shipment_id):
    URL = f"https://{factory_code}.haishenxiyi.net/api/shipment/picking"
    body_data = [
        shipment_id
    ]
    response = requests.post(URL,headers=headers,json=body_data)
    print(URL)
    print("Response Text:", response.text)

#打包
def package_barcode(factory_code, barcode):
    URL = f"https://{factory_code}.haishenxiyi.net/api/product/package/{barcode}/detail"
    response = requests.get(URL,headers=headers)
    result = json.loads(response.text)
    code = result.get('code')
    print(URL)
    print("Response Text:", response.text)
    if code == 200:
        print('打包详情成功！')
        scan_url = f"https://{factory_code}.haishenxiyi.net/api/product/package/{barcode}/scan"
        scan_response = requests.post(scan_url,headers=headers)
        print(scan_url)
        print(scan_response.text)
    else:
        print('打包详情失败！')

#出厂
def out_factory(factory_code,express_no) -> int:
    url = f"https://{factory_code}.haishenxiyi.net/api/product/outFactory/{express_no}"
    response = requests.post(url, headers=headers)
    print(url)
    print(response.text)
    result = json.loads(response.text)
    code = result.get('code')
    return code

def shipment_run(factory_code,order_no):
    connection = factory_connection(factory_code)
    cursor = connection.cursor()
    cursor.execute(f'SELECT id FROM opr_shipment WHERE order_no = "{order_no}" and flag & 512 != 512')
    results = cursor.fetchall()
    cursor.close()
    # rabbit: RabbitMQ = RabbitMQ(
    #     host='127.0.0.1',
    #     address='b-32ddf5af-5a01-4082-b593-534d3bb66a1f.mq.cn-northwest-1.amazonaws.com.cn',
    #     port=5671,
    #     ssl=True,
    #     # virtual_host='/',
    #     username='waterfall',
    #     password='Aog7B*rC&Yd@szL2'
    # )
    for row in results:
        shipment_ids = row
        shipment_id = shipment_ids[0]
        #校验物流是否下发成功
        check_express_status(factory_code,order_no,shipment_id)
        connection = factory_connection(factory_code)
        cursor = connection.cursor()
        cursor.execute(f'SELECT express_no,carrier FROM opr_shipment WHERE id = {shipment_id}')
        ex_results = cursor.fetchone()
        print(ex_results)
        express_no = ex_results[0]
        carrier = ex_results[1]
        if express_no is not None and carrier is not None:
            # message_data = {
            #     'no': express_no,
            #     'carrier': carrier
            # }
            #发送取消物流的消息
            with RabbitMQ(rabbitmq_source) as rabbit:
                rabbit.send(
                    message={
                        'no': express_no,
                        'carrier': carrier
                    },
                    routing_key='express.order.cancel'
                )
            #rabbit.send_message('', 'express.order.cancel', message_data)
            #拣货
            picking_barcode(factory_code, shipment_id)
            cursor.execute(f'SELECT barcode FROM opr_product WHERE shipment_id = {shipment_id} and companion_id is null and flag & 512 != 512')
            b_results = cursor.fetchall()
            for row in b_results:
                barcodes = row
                barcode = barcodes[0]
                #装箱
                package_barcode(factory_code, barcode)
            #出厂
            code = out_factory(factory_code,express_no)
            #if code != 500:
            # message_status = {
            #     'no': express_no,
            #     'carrier': carrier,
            #     'status': 'DELIVERED'
            # }
            #发送物流签收状态
            with RabbitMQ(rabbitmq_source) as rabbit:
                rabbit.send(
                    message={
                        'no': express_no,
                        'carrier': carrier,
                        'status': 'DELIVERED'
                    },
                    exchange='express.parcel.status'
                )
            #rabbit.send_message('express.parcel.status', '', message_status)
    close_connection(connection)

#执行
def barcode_run(factory_code, order_no):
    connection = factory_connection(factory_code)
    cursor = connection.cursor()
    cursor.execute(f"SELECT barcode FROM opr_product WHERE shipment_id in (SELECT id FROM opr_shipment WHERE order_no = '{order_no}' and flag & 512 != 512)  and companion_id is null and flag & 512 != 512")
    result = cursor.fetchall()
    for row in result:
        barcodes = row
        barcode = barcodes[0]
        print(barcode)
        #质检
        product_qualified(factory_code,barcode)
        #配附件
        attachment_scan(factory_code,barcode)
        #包装
        wrap_barcode(factory_code,barcode)
    close_connection(connection)



with open(file_path, 'r') as file:
    lines = file.readlines()

for line in lines:
    splited = line.split("\t")

    if len(splited) <= 1:
        order_no = splited[0].strip()
        factory_code = None
    else:
        factory_code = splited[0].strip()
        order_no = splited[1].strip()

    if not factory_code:
        for item in sql_list:
            print(item)
            factory_code = get_fcodebyorder(order_no, item)
            if factory_code:
                if item == 'pn':
                    rabbitmq_source = 'wf'
                else:
                    rabbitmq_source = item  
                break
            else:
               print("未找到 工厂代码")

    if not factory_code:
        print('fcode为空')
        continue
    barcode_run(factory_code, order_no)
    shipment_run(factory_code,order_no)